package com.hntx.joymusic.yun;


import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class HmacUtils {


    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";

	/*
	 * 展示了一个生成指定算法密钥的过程 初始化HMAC密钥
	 * @return
	 * @throws Exception
	 *
	  public static String initMacKey() throws Exception {
	  //得到一个 指定算法密钥的密钥生成器
	  KeyGenerator KeyGenerator keyGenerator =KeyGenerator.getInstance(MAC_NAME);
	  //生成一个密钥
	  SecretKey secretKey =keyGenerator.generateKey();
	  return null;
	  }
	 */

    /**
     * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
     *
     * @param encryptText 被签名的字符串
     * @param encryptKey  密钥
     * @return
     * @throws Exception
     */
    public static String HmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        //用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = encryptText.getBytes(ENCODING);
        //完成 Mac 操作
//        mac.doFinal(text);
        return Base64.encodeToString(mac.doFinal(text), Base64.NO_WRAP);
    }

    public static byte[] hmacsha1(byte[] source, byte[] key) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key, MAC_NAME);
            Mac mac = Mac.getInstance(MAC_NAME);
            mac.init(signingKey);
            return mac.doFinal(source);
        } catch (NoSuchAlgorithmException e) {
            return new byte[0];
        } catch (InvalidKeyException var5) {
            return new byte[0];
        }
    }

    public static String hmacsha1(String source, String key) {
        try {
            return tohex(hmacsha1(source.getBytes(ENCODING), key.getBytes(ENCODING)));
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    public static String hex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    private static final char[] HEX = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static String tohex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(HEX[bytes[i] >> 4 & 15]).append(HEX[bytes[i] & 15]);
        }
        return sb.toString();
    }
}
